<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/24
 * Time: 23:50
 */

namespace app\api\service;


use app\lib\Exception\TokenException;
use app\lib\power;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    protected static function generateToken()
    {
        $randChar = getRandChar(32);
        $timeStrmp = $_SERVER['REQUEST_TIME'];
        $code_seit = config('wx.rand_key');

        return sha1($randChar . $timeStrmp . $code_seit);
    }

    public static function getUid()
    {
        $uid = self::getTokenValue('uid');
        $prowe = self::getTokenValue('chmod');
        if($prowe == power::Father) {
            $userID = input('get.uid');
            if (!$userID) {
                throw new Exception('我觉得不行', 888);
            }
            return $userID;
        }else{
            return $uid;
        }
    }

    protected static function getTokenValue($key)
    {
        $token = Request::instance()->header('token');
        $var = Cache::get($token);
        if(!$var) {
            throw new TokenException([
                'message' => 'TOKEN已经过期，或不存在',
                'code' => 400,
                'error_code' => 10003
            ]);
        }else{
            if(!is_array($var)) {
                json_decode($var,true);
            }
            if(array_key_exists($key,$var)) {
                return $var[$key];
            }
            throw new Exception('在缓存中请求的变量不存在');
        }
    }

    public static function needExcludePower()
    {
        $power = self::getTokenValue('power');
        if($power){
            if($power >= power::Son){
                return true;
            }else{
                throw new TokenException([
                    'message' => '请先登录'
                ]);
            }
            throw new TokenException([
                'message' => '您没有权限访问这里'
            ]);
        }
    }

    public static function needPrimaryPower()
    {
        $power = self::getTokenValue('power');
        if($power){
            if($power == power::Son){
                return true;
            }else{
                throw new TokenException([
                    'message' => '您没有权限访问这里'
                ]);
            }
            throw new TokenException([
                'message' => '您没有权限访问这里'
            ]);
        }
    }

    public static function needAdminPower()
    {
        $power = self::getTokenValue('power');
        if($power){
            if($power == power::Father){
                return true;
            }else{
                throw new TokenException([
                    'message' => '您没有权限访问这里'
                ]);
            }
            throw new TokenException([
                'message' => '您没有权限访问这里'
            ]);
        }
    }
}